# -*- coding: UTF-8 -*-
import os
import os.path
import sys
import re
import shutil
# wwm 12.4 引入为了进度条
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append(current_dir)
sys.path.append("..")

import ruamel.yaml as yaml
from ruamel.yaml.comments import CommentedMap
import string
from pyh import *
from case import *
from cash import *
import time
import traceback
import os

import sys
import _thread
from Auto_Code import subprocess
import queue
import logging
import operator
from misc import *

case_logger = logging.getLogger('case')
command_logger = logging.getLogger('command')
frame_logger = logging.getLogger('frame')


class case(object):
    """description of class"""
    name_str = "name"
    purpose_str = "purpose"
    author_str = "author"
    time_str = "time"
    history_str = "history"
    factory_str = "factory"
    model_str = "model"
    description_str = "description"
    information_str = "information"
    bundle_str = "bundle"
    version_str = "version"
    fpga_str = "FPGA version"
    ui_str = "UI version"
    app_str = "APP version"
    setup_str = "setup"
    tearoff_str = "tearoff"
    match_str = "match_pattern"
    search_path_str = "search_path"
    search_mode_str = "search_pattern"
    total_sample_num_str = "total_sample_num"
    # xml_path_str="xml_path"

    # description_key = [name_str, purpose_str, author_str, time_str, history_str, match_str, search_mode_str,
    #                    search_path_str, total_sample_num_str,xml_path_str]
    description_key = [name_str, purpose_str, author_str, time_str, history_str, match_str, search_mode_str,
                       search_path_str, total_sample_num_str]
    information_key = [factory_str, model_str]
    version_key = [fpga_str, ui_str, app_str]

    def __init__(self, description=None, information=None):
        self.description = {}
        self.information = {}
        self.run_cashs = {}
        # self.standard_cashs = {}
        # self.result = {}
        self.version = {}
        self.standard_bundle_list = {}
        self.run_bundle_list = {}
        self.result_bundle_list = {}
        self.cmdOutQueue = queue.Queue()
        self.case_file = ""
        if description is not None:
            # assert cmp(description.keys, self.description_key)
            if operator.eq(description.keys, self.description_key):
                raise YamlFormatError("description key error")
            self.description = description
        else:
            for key in self.description_key:
                self.description[key] = ""
        if information is not None:
            # assert cmp(information, self.information_key)
            if operator.eq(information, self.information_key):
                raise YamlFormatError("information key error")
            self.information = information
        else:
            for key in self.information_key:
                self.information[key] = ""

        for key in self.version_key:
            self.version[key] = None

    def setDescriptionAttribute(self, key, value):
        assert key in self.description
        self.description[key] = value

    def getDescriptionAttribute(self, key):
        assert key in self.description
        return self.description[key]

    def setInformationAttribute(self, key, value):
        assert key in self.information
        self.information[key] = value

    def getInformationAttribute(self, key):
        assert key in self.information
        return self.information[key]

    def setVersionAttribute(self, key, value):
        assert key in self.information
        self.version[key] = value

    def getVersionAttribute(self, key):
        assert key in self.version_key
        return self.version[key]

    def getStandardTopBundle(self,bundle_path=None):
        if bundle_path:
            return self.standard_bundle_list[bundle_path]
        else:
            index = len(self.standard_bundle_list)
            return self.standard_bundle_list[index]

    def getStandardBundle(self, index):
        return self.standard_bundle_list[index]

    def getStandardtBundleCount(self):
        return len(self.standard_bundle_list)

    def getStandardBundleList(self):
        return self.standard_bundle_list

    def newBundle(self, bundle_index=None,setup_command=None,tearoff_command=None):
        if bundle_index is None:
            index = len(self.standard_bundle_list) + 1
        else:
            # assert bundle_index not in list(self.standard_bundle_list.keys())
            index = bundle_index
        self.standard_bundle_list[index] = {}
        self.standard_bundle_list[index][self.setup_str] =setup_command if setup_command else []
        self.standard_bundle_list[index][self.tearoff_str] = tearoff_command if tearoff_command else []
        self.run_bundle_list[index] = {}
        self.result_bundle_list[index] = {}
        return self.standard_bundle_list

    def getRunTopBundle(self,bundle_path=None):
        if bundle_path:
            return self.run_bundle_list[bundle_path]
        else:
            index = len(self.run_bundle_list)
            return self.run_bundle_list[index]

    def getRunBundle(self, index):
        return self.run_bundle_list[index]

    def getRunBundleCount(self):
        return len(self.run_bundle_list)

    def getRunBundleList(self):
        return self.run_bundle_list

    def getResultTopBundle(self,bundle_path=None):
        # wwm 1.14 bug
        if bundle_path:
            return self.result_bundle_list[bundle_path]
        else:
            index=len(self.result_bundle_list)
            return self.result_bundle_list[index]

    def getResultBundle(self, index):
        return self.result_bundle_list[index]

    def getResultBundleCount(self):
        return len(self.result_bundle_list)

    def getResultBundleList(self):
        return self.result_bundle_list

    def addStandardCash(self, c,bundle_path):
        assert isinstance(c, cash)
        # print self.standard_bundle_list
        standard_bundle = self.getStandardTopBundle(bundle_path)
        # print standard_bundle
        run_bundle = self.getRunTopBundle(bundle_path)
        result_bundle = self.getResultTopBundle(bundle_path)
        index = len(standard_bundle) - 2 + 1  # -2是因为有setup和setoff  +1是因为要增加一个 cash是从1开始的
        standard_bundle[index] = c
        run_bundle[index] = cash(index)
        run_bundle[index].setCashAttribute(cash.after_break_str, c.getCashAttribute(cash.after_break_str))
        result_bundle[index] = False

    def getStandardCash(self, bundle_index, cash_index):
        return self.standard_bundle_list[bundle_index][cash_index]

    def setStandardCash(self, bundle_index, cash_index, c):
        self.standard_bundle_list[bundle_index][cash_index] = c

    def getRunCash(self, bundle_index, cash_index):
        return self.run_bundle_list[bundle_index][cash_index]

    def setRunCash(self, bundle_index, cash_index, c):
        self.run_bundle_list[bundle_index][cash_index] = c

    def getResult(self, bundle_index, cash_index):
        return self.result_bundle_list[bundle_index][cash_index]

    def setResult(self, bundle_index, cash_index, flag):
        self.result_bundle_list[bundle_index][cash_index] = flag

    def addCash(self, c,bundle_path):
        assert isinstance(c, cash)
        self.addStandardCash(c,bundle_path)

    def addBundleSetup(self, command_list):
        bundle = self.getStandardTopBundle()
        bundle[self.setup_str] = command_list

    def addBundleTearoff(self, command_list):
        bundle = self.getStandardTopBundle()
        bundle[self.tearoff_str] = command_list

    def runCash(self, bundle_index, cash_index, h_pip):
        case_logger.info("cash:%d" % (cash_index))
        std_cash = self.standard_bundle_list[bundle_index][cash_index]
        run_cash = self.run_bundle_list[bundle_index][cash_index]
        cmd_str = 'load --adc0 %s \n' % std_cash.geFileAttribute(cash.adc_0_str)
        h_pip.stdin.write(cmd_str.encode("UTF-8"))
        h_pip.stdin.flush()
        command_logger.debug("send =>" + cmd_str)
        if not self.checkCommand():
            return False
        cmd_str = 'load --adc1 %s \n' % std_cash.geFileAttribute(cash.adc_1_str)
        h_pip.stdin.write(cmd_str.encode("UTF-8"))
        h_pip.stdin.flush()
        command_logger.debug("send =>" + cmd_str)
        if not self.checkCommand():
            return False
        cmd_str = 'load --cis_top %s \n' % std_cash.geFileAttribute(cash.cis_top_str)
        h_pip.stdin.write(cmd_str.encode("UTF-8"))
        h_pip.stdin.flush()
        command_logger.debug("send =>" + cmd_str)
        if not self.checkCommand():
            return False
        cmd_str = 'load --cis_bottom %s \n' % std_cash.geFileAttribute(cash.cis_bottom_str)
        h_pip.stdin.write(cmd_str.encode("UTF-8"))
        h_pip.stdin.flush()
        command_logger.debug("send =>" + cmd_str)
        if not self.checkCommand():
            return False

        if (std_cash.getCashAttribute(cash.after_break_str)):
            cmd_str = 'mark --after_break %s \n' % std_cash.getCashAttribute(cash.after_break_str)
            h_pip.stdin.write(cmd_str.encode("UTF-8"))
            h_pip.stdin.flush()
            command_logger.debug("send =>" + cmd_str)
            if not self.checkCommand():
                return False

        cmd_str = 'run \n'
        h_pip.stdin.write(cmd_str.encode("UTF-8"))
        h_pip.stdin.flush()
        command_logger.debug("send =>" + cmd_str)
        if not self.checkRunCommand(bundle_index, cash_index):
            return False

        str = "result: "
        for key in cash.attribute_key:
            temp_str = self.run_bundle_list[bundle_index][cash_index].getCashAttribute(key)
            str = str + (" %s:%s ") % (key, temp_str)
        case_logger.info(str)

        return True

    def runScript(self, bundle_index, script_name, h_pip):
        assert script_name == self.setup_str or script_name == self.tearoff_str

        command_list = self.standard_bundle_list[bundle_index][script_name]
        print("command_list:{}".format(command_list))
        self.result_bundle_list[bundle_index][script_name] = {}
        for command in command_list:
            self.result_bundle_list[bundle_index][script_name][command] = False
        for command in command_list:
            h_pip.stdin.write(('%s \n' % command).encode("utf-8"))
            h_pip.stdin.flush()
            command_logger.debug("send => %s \n" % command)
            if not self.checkCommand():
                error_str = "bundle %s %s script failed : %s!" % (bundle_index, script_name, command)
                case_logger.error(error_str)
                # return False
                raise Exception(error_str)
            else:
                self.result_bundle_list[bundle_index][script_name][command] = True

        case_logger.info("%s script process success" % (script_name))
        return True

    #
    # def run(self, file_app,case_total_num,case_load_num,pk=None):
    #     try:
    #         while not self.cmdOutQueue.empty():
    #             self.cmdOutQueue.get()
    #         # 跳转当前路径
    #
    #         #12.27wwm
    #         from file_manage import models
    #         File_database=models.File.objects.get(pk=pk)
    #         #
    #         app_path_exclude = os.path.split(file_app)
    #         p = subprocess.Popen(file_app,stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=app_path_exclude[0])
    #         _thread.start_new_thread(self.listenStdout, (p,))
    #
    #         try:
    #             for bundle_index in self.result_bundle_list:
    #                 progress_bar = progressBar(20, "bundle %d progress:"%bundle_index)
    #                 self.clearStdout(50)
    #                 case_logger.info("--------------------------------------------------bundle %d/%d--------------------------------------------------"%(bundle_index,len(self.result_bundle_list)))
    #                 num_cash_in_bundle = len(self.result_bundle_list[bundle_index])
    #                 index = 0
    #                 if self.runScript(bundle_index, self.setup_str, p): #run setup script
    #                     for cash_index in self.result_bundle_list[bundle_index]: #run all cash
    #                         if cash_index == self.setup_str or cash_index == self.tearoff_str:
    #                             continue
    #                         index = index +1
    #                         case_load_num[0]+=1
    #                         #设定启动时间 wwm 1.6
    #                         start = time.time()
    #                         if self.runCash(bundle_index, cash_index, p):
    #                             progress_bar.draw(100*index/num_cash_in_bundle)
    #                             #12.5 wwm
    #                             File_database.set_progress_bar_value(float("%.2f"%(100.0*case_load_num[0]/case_total_num)))
    #
    #                             self.result_bundle_list[bundle_index][cash_index] = self.getStandardCash(bundle_index,cash_index).CompareCash( self.getRunCash(bundle_index,cash_index),self.getDescriptionAttribute(self.match_str))
    #                         end = time.time()
    #                         runtime = end - start
    #                         # m, s = divmod(runtime, 60)
    #                         # h, m = divmod(m, 60)
    #                         tmp_cash_dic=self.getRunCash(bundle_index, cash_index)
    #                         tmp_cash_dic.setCashAttribute(cash.time_str,"%.4f s"%(runtime))
    #                         # tmp_cash_dic.dictionary[cash.time_str]="{0}s".format(runtime)
    #
    #                 self.runScript( bundle_index, self.tearoff_str, p) # run tearoff script
    #                 print("\n")
    #
    #         finally:
    #             print("\n")
    #             time.sleep(1)
    #             while not self.cmdOutQueue.empty():
    #                 self.cmdOutQueue.get()
    #             cmd_str = 'bye\n'
    #             p.stdin.write(cmd_str.encode("UTF-8"))
    #             p.stdin.flush()
    #             command_logger.debug("send =>"+cmd_str)
    #     except Exception as e:
    #         error_str = "Error in case.run! (%s)"%e
    #         case_logger.error(error_str)
    #         raise Exception(error_str)
    #     return True
    #通过样本路径下有多少文件夹来判断bundle_list（包含默认文件夹）
    def get_self_bundle_list(self,setup_command,tearoff_command):
        search_path=self.description[self.search_path_str]
        for root,dirnames,filenames in os.walk(search_path):
            if not filenames: # 没有文件则跳过这个文件夹
                continue
            for filename in filenames:
                name, ext = os.path.splitext(filename)
                if ".raw" == ext and "adc0" in name: #说明这个文件夹下有样本 就创建一个bundle
                    self.newBundle(root,setup_command,tearoff_command)




    # wwm 1.14
    def run_cash_and_add(self, file_app, case_total_num, case_load_num, pk=None):
        try:
            while not self.cmdOutQueue.empty():
                self.cmdOutQueue.get()
            # 跳转当前路径

            # 12.27wwm
            if pk != None:
                from file_manage import models
                File_database = models.File.objects.get(pk=pk)
            #
            app_path_exclude = os.path.split(file_app)
            # self.description[self.search_path_str]
            # if self.description[self.xml_path_str]!='.' or self.description[self.xml_path_str]!='' or self.description[self.xml_path_str] is not None:
            #     xml_filename=self.description[self.xml_path_str].split('/')[-1]
            #     print("替换xml开始",xml_filename)
            #     old_xml_path=os.path.join(str(app_path_exclude[0]),"xml",xml_filename)
            #     if os.path.exists(old_xml_path):
            #         os.remove(old_xml_path)
            #     shutil.copyfile(old_xml_path,self.description[self.xml_path_str])
            #     print("替换xml完成", self.description[self.xml_path_str])
            p = None
            # _thread.start_new_thread(self.listenStdout, (p,))
            self.max_cost_time = "0"
            # for index in self.load_file_path_list():
            #bundle_index为目录下的文件
            num_cash_in_bundle = int(case_total_num)
            index = 0
            print("self.standard_bundle_list:",self.standard_bundle_list)
            for bundle_index in self.result_bundle_list:# bundle_index为某个bundle的路径path
                try:
                    progress_bar = progressBar(20, 'bundle {} progress:'.format(bundle_index))
                    self.clearStdout(50)
                    case_logger.info(
                        "--------------------------------------------------bundle {}/{}--------------------------------------------------".format(
                            bundle_index, len(self.result_bundle_list)))
                    # num_cash_in_bundle = len(self.result_bundle_list[bundle_index])
                    for filename in os.listdir(bundle_index):
                        font_name,ext=os.path.splitext(filename)
                        if ext==".xml":
                            xml_path=os.path.join(bundle_index,filename)
                            print("替换xml开始",filename)
                            old_xml_path=os.path.join(str(app_path_exclude[0]),"xml",filename)
                            print("老xml路径：{}---新xml路径:{}".format(old_xml_path,xml_path))
                            if os.path.exists(old_xml_path):
                                os.remove(old_xml_path)
                            print("替换xml完成", shutil.copyfile(xml_path,old_xml_path))
                    #替换完xml启动程序
                    p = subprocess.Popen(file_app,close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                         cwd=app_path_exclude[0])
                    print("启动p!")
                    _thread.start_new_thread(self.listenStdout, (p,))
                    if self.runScript(bundle_index, self.setup_str, p):  # run setup script
                        print("初始命令执行完毕！")
                        # for cash_index in self.result_bundle_list[bundle_index]:  # run all cash
                        # wwm 1.14 generator!
                        for cash_index in self.load_file_path_list(bundle_index):
                            # print("self.load_file_path_list执行完毕",cash_index)
                            if cash_index == self.setup_str or cash_index == self.tearoff_str:
                                continue
                            index = index + 1
                            case_load_num[0] += 1
                            # 设定启动时间以计算样本消耗时间 wwm 1.6
                            start = time.time()
                            if self.runCash(bundle_index, cash_index, p):
                                progress_bar.draw(100 * index / num_cash_in_bundle)
                                # 12.5 wwm
                                if pk != None:
                                    File_database.set_progress_bar_value(
                                        float("%.2f" % (100.0 * case_load_num[0] / int(case_total_num))))

                                self.result_bundle_list[bundle_index][cash_index] = self.getStandardCash(
                                    bundle_index,
                                    cash_index).CompareCash(
                                    self.getRunCash(bundle_index, cash_index),
                                    self.getDescriptionAttribute(self.match_str),
                                    self.description[self.search_mode_str])
                            end = time.time()
                            runtime = end - start
                            runtime_str = "%.4f s" % (runtime)
                            tmp_cash_dic = self.getRunCash(bundle_index, cash_index)
                            tmp_cash_dic.setCashAttribute(cash.time_str, runtime_str)
                            if runtime_str > self.max_cost_time:
                                self.max_cost_time = runtime_str

                    self.runScript(bundle_index, self.tearoff_str, p)  # run tearoff script
                    print("\n")
                finally:
                    print("\n")
                    time.sleep(1)
                    while not self.cmdOutQueue.empty():
                        self.cmdOutQueue.get()
                    cmd_str = 'bye\n'
                    p.stdin.write(cmd_str.encode("UTF-8"))
                    p.stdin.flush()
                    command_logger.debug("send =>" + cmd_str)
            #
            # finally:
            #     print("\n")
            #     time.sleep(1)
            #     while not self.cmdOutQueue.empty():
            #         self.cmdOutQueue.get()
            #     cmd_str = 'bye\n'
            #     p.stdin.write(cmd_str.encode("UTF-8"))
            #     p.stdin.flush()
            #     command_logger.debug("send =>" + cmd_str)
        except Exception as e:
            error_str = "Error in case.run_and_add! (%s)" % e
            case_logger.error(error_str)
            raise Exception(error_str)
        return True

    def load_file_path_list(self,bundle_path):
        """flag:文件夹或文件名匹配
        返回生成的cash信息，便于赋值到standard_cash"""
        # 获取信息模式  0 文件夹匹配 1 文件匹配
        cash_flag = int(self.description[self.search_mode_str])
        # path = self.description[self.search_path_str]
        path = bundle_path
        assert os.path.exists(path)
        # dirFilselist = []
        # cashlist = []
        index = 0
        # test_case = case()
        temp_list = []
        if (cash_flag == 0):
            # 规定表达式匹配格式  (文件夹匹配方式)
            #     value_pattern=re.compile(r'/value-([0-9]+)/')    #第一组
            #     currency_pattern=re.compile(r'/([A-Z]{3})/')   #第一组
            #     version_pattern=re.compile(r'/version-([0-9]{1,3}).*?/')   #第一组
            #     error_code_pattern=re.compile(r'/([0-9]{3})/')    #第一组
            #     CIS_pattern=re.compile(r'/(CIS_)(.*?)/')    #第二组
            #     direction_pattern=re.compile("/(direction-)([A-D])/")  #第二组
            #     factory_pattern=re.compile(r'/(CIS_.*?)/(.*?)/')   #第二组
            #     sn_pattern=re.compile(r'/version-.*?/(.*?)/direction-')   #第一组
            value_pattern = re.compile(r'/value-([0-9]+)/')  # 第一组
            currency_pattern = re.compile(r'ample/([A-Z]{3})/')  # 第一组
            # version_pattern = re.compile(r'/version-([0-9]{1,4})-.*?')  # 第一组
            version_pattern = re.compile(r'/version-([0-9]{1,4})(.*)?')  # 第一组
            error_code_pattern = re.compile(r'CIS_.*?/([0-9]{1,4})/')  # 第一组
            CIS_pattern = re.compile(r'/(CIS_)(.*?)/')  # 第二组
            direction_pattern = re.compile("(sion-.*?)/([A-D])/")  # 第二组
            factory_pattern = re.compile(r'/(CIS_.*?)/(.*?)/')  # 第二组
            sn_pattern = re.compile(r'/version-.*?/(.*?)/direction-')  # 第一组
        else:
            #  文件名匹配方式!
            # 20191108_111359_1_Model_JL_CNY_Err177_LastErr0x0_Den100_Dir0_Ver15_SN_BD14527154_cis_top.bmp
            value_pattern = re.compile(r'_Den(.*?)_')
            # currency_pattern = re.compile(r'/([A-Z]{3})/')
            currency_pattern = re.compile(r'_([A-Z]{3})_Err')
            version_pattern = re.compile(r'_Ver(.*?)_')
            error_code_pattern = re.compile(r'_Err(.*?)_')  # 第一组
            # CIS_pattern = re.compile(r'/(CIS_)(.*?)/')  # 第二组
            direction_pattern = re.compile("_Dir([A-D0-4]{1})_")  # 第二组
            # 机型和冠字号匹配是个问题？  暂时先用读取位置代替
            factory_pattern = re.compile(r'/(CIS_.*?)/(.*?)/')  # 第二组
            sn_pattern = re.compile(r'_SN_(.*?)_')  # 第一组
            break_pattern = re.compile(r'_LastErr0x(.*?)_')  # 刹车相关 break?

        # count_total = 0
        factory_temp = ""
        currency_temp = ""
        version_temp = ""
        value_temp = ""
        sn_temp = ""
        error_code_temp = ""
        break_temp = ""
        for parent, dirnames, filenames in os.walk(path):
            #  wwm 10.24 读取文件夹信息
            if not filenames:
                continue
            if not dirnames and cash_flag == 0:
                # 文件夹匹配模式
                value_temp = value_pattern.search(parent)
                currency_temp = currency_pattern.search(parent)
                version_temp = version_pattern.search(parent)
                error_code_temp = error_code_pattern.search(parent)
                CIS_temp = CIS_pattern.search(parent)
                direction_temp = direction_pattern.search(parent)
                factory_temp = factory_pattern.search(parent)
                # 12.30 文件夹匹配不需要冠字号
                # sn_temp = sn_pattern.search(parent)
                sn_temp = ""
                if factory_temp:
                    self.setInformationAttribute(self.factory_str, factory_temp.group(2))
                # 没有匹配的相关值直接使其等于None
                temp_a = [currency_temp, version_temp, value_temp, sn_temp, error_code_temp]
                # 防止因为0而报错
                temp_list = [k.group(1) if k else None for k in temp_a]
                temp_list.append(False)
                if temp_list[0] == "CNY":
                    temp_list[1] = self.version_conversion(temp_list[1], temp_list[2])
            # err号单独处理
            # 最后一个刹车后暂时用False代替
            ##############################################

            for filename in filenames:
                name, ext = os.path.splitext(filename)
                if ".raw" == ext and "adc0" in name:
                    if (cash_flag == 1):
                        #  文件匹配模式
                        value_temp = value_pattern.search(filename)
                        currency_temp = currency_pattern.search(filename)
                        version_temp = version_pattern.search(filename)
                        error_code_temp = error_code_pattern.search(filename)
                        direction_temp = direction_pattern.search(filename)
                        factory_temp = factory_pattern.search(filename)
                        sn_temp = sn_pattern.search(filename)
                        break_temp = break_pattern.match(filename)
                        # 设置information factory信息
                        if factory_temp:
                            self.setInformationAttribute(self.factory_str, factory_temp.group(2))
                        # 没有匹配的相关值直接使其等于0
                        temp_a = [currency_temp, version_temp, value_temp, sn_temp, error_code_temp, break_temp]
                        temp_list = [k.group(1) if k else None for k in temp_a]
                        # 刹车单独处理
                        temp_list[5] = (False if (temp_list[5] == None) else True)

                        # #  是人民币的情况下 将version进行转换
                        # if temp_list[0] == "CNY" and cash_flag:
                        #     temp_list[1] = self.version_conversion(temp_list[1], temp_list[2])
                    ##########################
                    templist = name.split("_")  # list
                    lastDashLength = len(templist[len(templist) - 1])  # 4
                    tempStr = name[0:len(name) - lastDashLength]
                    adc0File = os.path.join(parent, tempStr + "adc0.raw")
                    adc1File = os.path.join(parent, tempStr + "adc1.raw")
                    topCISFile = os.path.join(parent, tempStr + "cis_top.bmp")
                    bottomCISFile = os.path.join(parent, tempStr + "cis_bottom.bmp")

                    if not os.path.isfile(adc0File):
                        print("can't open file %s" % adc0File)
                        continue
                    if not os.path.isfile(adc1File):
                        print("can't open file %s" % adc1File)
                        continue
                    if not os.path.isfile(topCISFile):
                        print("can't open file %s" % topCISFile)
                        continue
                    if not os.path.isfile(bottomCISFile):
                        print("can't open file %s" % bottomCISFile)
                        continue

                    # need test 4 files
                    tempCash = cash(index)

                    tempCash.setFileAttribute(tempCash.adc_0_str, adc0File)
                    tempCash.setFileAttribute(tempCash.adc_1_str, adc1File)
                    tempCash.setFileAttribute(tempCash.cis_top_str, topCISFile)
                    tempCash.setFileAttribute(tempCash.cis_bottom_str, bottomCISFile)

                    list(map(tempCash.setCashAttribute, tempCash.attribute_key, temp_list))
                    self.addCash(tempCash,bundle_path)

                    index = index + 1
                    yield index

    # 是人民币的情况下将ver进行转换
    @staticmethod
    def version_conversion(version_old, cash_value):
        if (version_old == "1"):
            return "90"
        elif (version_old == "2"):
            return "99"
        elif (version_old == "3"):
            # return "05"
            return "5"
        elif (version_old == "4"):
            if (cash_value == "100"):
                return "15"
            if (cash_value == "50"):
                return "18"
        elif (version_old == "5"):
            if (cash_value == "100"):
                return "1512"
            if (cash_value == "5"):
                return "20"
            if (cash_value == "1" or cash_value =="10" or cash_value =="20" or cash_value =="50"):
                return "19"
        else:
            return version_old

    # def loadFromYaml(self, file_yaml):
    #     y = yaml.YAML()
    #     y.allow_duplicate_keys = False
    #     try:
    #         with open(file_yaml, 'r') as infile:
    #             try:
    #                 yaml_dict = y.load(infile)
    #                 self.case_file = file_yaml
    #             except Exception as e:
    #                 error_str = "%s format error!(%s)" % (file_yaml, e)
    #                 case_logger.error(error_str)
    #                 raise YamlFormatError(error_str)
    #     except IOError as e:
    #         error_str = "open file %s failed! (%s)\n" % (file_yaml, e)
    #         case_logger.error(error_str)
    #         raise e
    #     except Exception as e:
    #         error_str = "Error in case.loadFromYaml(%s)" % e
    #         case_logger.error(error_str)
    #         raise Exception(error_str)
    #
    #     try:
    #         yaml_description_dict = yaml_dict[self.description_str]
    #         yaml_information_dict = yaml_dict[self.information_str]
    #         yaml_bundle_dict = yaml_dict[self.bundle_str]
    #
    #         for key in self.description_key:
    #             self.description[key] = yaml_description_dict[key]
    #
    #         for key in self.information_key:
    #             self.information[key] = yaml_information_dict[key]
    #
    #         for bundle_key in yaml_dict[self.bundle_str]:
    #             if operator.eq("bundle", bundle_key[0:5]):
    #                 raise YamlFormatError("Expect token \"bundle\", but \"%s\" found." % (bundle_key[0:5]))
    #             try:
    #                 bundle_index = int(bundle_key[6:])
    #             except Exception as e:
    #                 raise YamlFormatError("Expect token \"bundle+integer\", but \"%s\" found." % (bundle_key))
    #             bundle = self.newBundle(bundle_index)
    #             self.standard_bundle_list[bundle_index][self.setup_str] = yaml_bundle_dict[bundle_key][self.setup_str]
    #             self.standard_bundle_list[bundle_index][self.tearoff_str] = yaml_bundle_dict[bundle_key][
    #                 self.tearoff_str]
    #
    #             for cash_key in yaml_bundle_dict[bundle_key]:
    #                 if cash_key == self.setup_str or cash_key == self.tearoff_str:
    #                     continue
    #
    #                 if not isinstance(cash_key, int):
    #                     raise YamlFormatError("Expect token for integer, but \"%s\" found." % (cash_key))
    #
    #                 cash_index = cash_key
    #                 # #wwm 1.6
    #                 # tmp_dict=yaml_bundle_dict[bundle_key][cash_key]
    #                 # tmp_dict.append()
    #                 temp_cash = cash(cash_index, yaml_bundle_dict[bundle_key][cash_key])
    #                 self.standard_bundle_list[bundle_index][cash_index] = temp_cash
    #                 temp_cash = cash(cash_index)
    #                 temp_cash.setCashAttribute(cash.after_break_str,
    #                                            self.standard_bundle_list[bundle_index][cash_index].getCashAttribute(
    #                                                cash.after_break_str))
    #                 self.run_bundle_list[bundle_index][cash_index] = temp_cash
    #                 self.result_bundle_list[bundle_index][cash_index] = False
    #     except Exception as e:
    #         error_str = "Error in case.loadFromYaml(%s)" % e
    #         case_logger.error(error_str)
    #         raise Exception(error_str)
    #         # return False
    #
    #     return True

    def dumpToYaml(self, f):
        temp_bundle = CommentedMap()
        temp_bundle_list = CommentedMap()
        for bundle_index in range(1, len(self.standard_bundle_list) + 1):  # bundle1
            temp_bundle[self.setup_str] = self.standard_bundle_list[bundle_index][self.setup_str]
            temp_bundle[self.tearoff_str] = self.standard_bundle_list[bundle_index][self.tearoff_str]
            # for key in self.standard_bundle_list[bundle_index]:#bundle1 inside
            #     if key == self.setup_str or key == self.tearoff_str:
            #         continue
            #     assert isinstance(key, int)
            #     assert isinstance(self.standard_bundle_list[bundle_index][key], cash)
            #     temp_bundle[key] = self.standard_bundle_list[bundle_index][key].dictionary
            # if  isinstance(self.standard_bundle_list[bundle_index][key], cash):
            # temp_bundle[key] = self.standard_bundle_list[bundle_index][key].dictionary
            temp_bundle_list["bundle%d" % bundle_index] = temp_bundle
        return yaml.dump({self.information_str: self.information, self.description_str: self.description,
                          self.bundle_str: temp_bundle_list}, f, Dumper=yaml.RoundTripDumper)

    def __str__(self):
        temp_bundle = CommentedMap()
        temp_bundle_list = CommentedMap()
        for bundle_index in range(1, len(self.standard_bundle_list) + 1):
            temp_bundle[self.setup_str] = self.standard_bundle_list[bundle_index][self.setup_str]
            temp_bundle[self.tearoff_str] = self.standard_bundle_list[bundle_index][self.tearoff_str]
            for key in self.standard_bundle_list[bundle_index]:
                if key == self.setup_str or key == self.tearoff_str:
                    continue
                assert isinstance(key, int)
                assert isinstance(self.standard_bundle_list[bundle_index][key], cash)
                temp_bundle[key] = self.standard_bundle_list[bundle_index][key].dictionary
            # for cash_index in range(1,len(self.standard_bundle_list[bundle_index])+1):
            # temp_bundle[cash_index] = self.standard_bundle_list[bundle_index][cash_index].dictionary
            temp_bundle_list["bundle%d" % bundle_index] = temp_bundle
        return yaml.dump({self.description_str: self.description, self.information_str: self.information,
                          self.bundle_str: temp_bundle_list}, Dumper=yaml.RoundTripDumper)

    def __repr__(self):
        temp_bundle = CommentedMap()
        temp_bundle_list = CommentedMap()
        for bundle_index in range(1, len(self.standard_bundle_list) + 1):
            temp_bundle[self.setup_str] = self.standard_bundle_list[bundle_index][self.setup_str]
            temp_bundle[self.tearoff_str] = self.standard_bundle_list[bundle_index][self.tearoff_str]
            for key in self.standard_bundle_list[bundle_index]:
                if key == self.setup_str or key == self.tearoff_str:
                    continue
                assert isinstance(key, int)
                assert isinstance(self.standard_bundle_list[bundle_index][key], cash)
                temp_bundle[key] = self.standard_bundle_list[bundle_index][key].dictionary
            # for cash_index in range(1,len(self.standard_bundle_list[bundle_index])+1):
            # temp_bundle[cash_index] = self.standard_bundle_list[bundle_index][cash_index].dictionary
            temp_bundle_list["bundle%d" % bundle_index] = temp_bundle
        return yaml.dump({self.description_str: self.description, self.information_str: self.information,
                          self.bundle_str: temp_bundle_list}, Dumper=yaml.RoundTripDumper)

    # Functions for generate report
    def tableDsprCss(self, table=None, width='90%'):
        table.attributes['cellSpacing'] = 1;
        table.attributes['cellPadding'] = 1;
        table.attributes['border'] = 1;
        table.attributes['borderColor'] = '#666666';
        table.attributes['width'] = width;

    def tablecss(self, table=None, width='90%'):
        table.attributes['cellSpacing'] = 1;
        table.attributes['cellPadding'] = 1;
        table.attributes['border'] = 1;
        table.attributes['borderColor'] = '#666666';
        table.attributes['width'] = width;

    def tr_title_css(self, tr=None):
        tr.attributes['bgcolor'] = '#CCCC00';

    def genCaseReport(self, fileName):
        # display some general information(time, version etc.) of report
        table_head_color_green = "#66B3FF"
        table_head_color_red = "#FF0033"
        page = PyH('Test Case (%s) Report' % self.getDescriptionAttribute(case.name_str))
        page << '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
        title_div = div(b('Test Case \"%s\" Report' % self.getDescriptionAttribute(case.name_str)), id='myCSSid1')
        page << title_div
        curr_time = time.strftime("%Y-%m-%d %X", time.localtime())
        case_information_div = div()
        case_description_div = div()

        case_description_div << span("Generate Data: %s" % curr_time) << br()
        # case_description_div << span("case file: %s"% self.case_file, href=self.case_file) << br()
        # case_description_div << a("case file: %s"% self.case_file, href=self.case_file) << br()
        case_description_div << span("case file: ")
        case_description_div << a("%s" % self.case_file, href=self.case_file) << br()
        for key in case.description_key:
            case_description_div << span("%s: %s" % (key, self.getDescriptionAttribute(key))) << br()
        page << case_description_div

        for key in case.information_key:
            case_information_div << span("%s: %s" % (key, self.getInformationAttribute(key))) << br()
        page << case_information_div

        case_status_div = div()
        all_num = 0
        pass_num = 0
        fail_num = 0
        bundle_cash_num = {}
        bundle_pass_num = {}
        bundle_pass_status = {}

        # Do some statistical work
        for bundle_index in self.result_bundle_list:
            result_bundle = self.getResultBundle(bundle_index)
            bundle_cash_num[bundle_index] = len(result_bundle)
            bundle_pass_num[bundle_index] = 0
            for key in result_bundle:
                if key != 'setup' and key != 'tearoff':
                    all_num = all_num + 1
                    if result_bundle[key]:
                        pass_num = pass_num + 1
                        bundle_pass_num[bundle_index] = bundle_pass_num[bundle_index] + 1
                    else:
                        fail_num = fail_num + 1
            if bundle_cash_num[bundle_index] == bundle_pass_num[bundle_index]:
                bundle_pass_status[bundle_index] = True
            else:
                bundle_pass_status[bundle_index] = False

        # Display summary information
        case_status_div << span("Test Result:")
        if fail_num == 0:
            case_status_div << span("Passed", style="color:green") << br()
        else:
            status_str = "Failed"
            case_status_div << span("Failed", style="color:red") << br()
        page << case_status_div

        page << a(name='h_summary')
        page << div(b('Summary'), id='myCSSid1')

        version_div = div()
        for key in case.version_key:
            version_div << span("%s: %s" % (key, self.getVersionAttribute(key))) << br()
        page << version_div

        summary_div = div()
        summary_div << span("Total cases:%d" % all_num) << br()
        summary_div << span("Passed cases:%d" % pass_num) << br()
        if fail_num != 0:
            summary_div << span("Failed cases:%d" % fail_num, style="color:red") << br()
        summary_div << span("max_cost_time:%s" % self.max_cost_time) << br()
        page << summary_div

        # 1.7 记录最大时间 wwm
        span_div = div(style="border:1px ;height:20px")
        page << span_div
        if fail_num != 0:
            page << a("Failed summary:")
            tableSummary = page << table()
            self.tablecss(tableSummary)
            titleTrSummary = tableSummary << tr()
            titleTrSummary << td('index', bgcolor=table_head_color_red, align="center")
            titleTrSummary << td('status', bgcolor=table_head_color_red, align="center")
            titleTrSummary << td('result', bgcolor=table_head_color_red, align="center")
            for key in cash.attribute_key:
                titleTrSummary << td(key, bgcolor=table_head_color_red, align="center")
            # wwm 1.6
            for key in cash.not_run_attribute_key:
                titleTrSummary << td(key, bgcolor=table_head_color_green, align="center")
            titleTrSummary << tr() << tr()

            valueTrSummary = tableSummary << tr()
            for bundle_index in self.result_bundle_list:
                # for index in range(0,self.getLength()):
                if bundle_pass_status[bundle_index]:
                    valueTrSummary << td(colspan="9", align="center", bgcolor="green") << a("bundle %s" % bundle_index,
                                                                                            href="#h_bundle%s" % bundle_index) << tr() << tr()
                    continue
                else:
                    valueTrSummary << td(colspan="9", align="center", bgcolor="red") << a("bundle %s" % bundle_index,
                                                                                          href="#h_bundle%s" % bundle_index) << tr()

                for cash_index in self.result_bundle_list[bundle_index]:
                    if cash_index == self.setup_str or cash_index == self.tearoff_str:
                        continue
                    assert isinstance(cash_index, int)
                    assert cash_index > 0
                    if self.result_bundle_list[bundle_index][cash_index]:
                        continue
                    standard_cash = self.standard_bundle_list[bundle_index][cash_index]
                    result_cash = self.run_bundle_list[bundle_index][cash_index]

                    valueTrSummary << td(rowspan="2", align="center") << a('%d' % cash_index,
                                                                           href="#h_bundle%s_case%d" % (
                                                                               bundle_index, cash_index))
                    # if self.getResult(index):
                    if self.result_bundle_list[bundle_index][cash_index]:
                        valueTrSummary << td(rowspan="2", align="center", bgcolor="green") << a('%s' % "pass")
                    else:
                        valueTrSummary << td(rowspan="2", align="center", bgcolor="red") << a('%s' % "failed")

                    valueTrSummary << td('%s' % "GOLDEN", bgcolor="grey", align="center")

                    for key in cash.attribute_key:
                        valueTrSummary << td("%s" % standard_cash.getCashAttribute(key), bgcolor="grey", align="center")
                    for key in cash.not_run_attribute_key:
                        valueTrSummary << td("----", bgcolor="grey", align="center")
                    valueTrSummary = tableSummary << tr()
                    valueTrSummary << td('%s' % "RUN", align="center")
                    for key in cash.attribute_key:
                        valueTrSummary << td("%s" % result_cash.getCashAttribute(key), align="center")
                    for key in cash.not_run_attribute_key:
                        tmp = result_cash.getCashAttribute(key)
                        valueTrSummary << td("%s" % tmp, align="center")

                    valueTrSummary = tableSummary << tr()
        span_div = div(style="border:1px ;height:20px")
        page << span_div

        if pass_num != 0:
            page << a("Pass summary:")
            tableSummary = page << table()
            self.tablecss(tableSummary)
            titleTrSummary = tableSummary << tr()
            titleTrSummary << td('index', bgcolor=table_head_color_green, align="center")
            titleTrSummary << td('status', bgcolor=table_head_color_green, align="center")
            titleTrSummary << td('result', bgcolor=table_head_color_green, align="center")
            for key in cash.attribute_key:
                titleTrSummary << td(key, bgcolor=table_head_color_green, align="center")
            # wwm 1.6
            for key in cash.not_run_attribute_key:
                titleTrSummary << td(key, bgcolor=table_head_color_green, align="center")

            titleTrSummary << tr() << tr()

            valueTrSummary = tableSummary << tr()
            for bundle_index in self.result_bundle_list:
                # for index in range(0,self.getLength()):
                if bundle_pass_status[bundle_index]:
                    valueTrSummary << td(colspan="9", align="center", bgcolor="green") << a("bundle %s" % bundle_index,
                                                                                            href="#h_bundle%s" % bundle_index) << tr() << tr()
                else:
                    valueTrSummary << td(colspan="9", align="center", bgcolor="red") << a("bundle %s" % bundle_index,
                                                                                          href="#h_bundle%s" % bundle_index) << tr()

                for cash_index in self.result_bundle_list[bundle_index]:
                    if cash_index == self.setup_str or cash_index == self.tearoff_str:
                        continue
                    assert isinstance(cash_index, int)
                    assert cash_index > 0
                    if not self.result_bundle_list[bundle_index][cash_index]:
                        continue
                    standard_cash = self.standard_bundle_list[bundle_index][cash_index]
                    result_cash = self.run_bundle_list[bundle_index][cash_index]

                    valueTrSummary << td(rowspan="2", align="center") << a('%d' % cash_index,
                                                                           href="#h_bundle%s_case%d" % (
                                                                               bundle_index, cash_index))
                    # if self.getResult(index):
                    if self.result_bundle_list[bundle_index][cash_index]:
                        valueTrSummary << td(rowspan="2", align="center", bgcolor="green") << a('%s' % "pass")
                    else:
                        valueTrSummary << td(rowspan="2", align="center", bgcolor="red") << a('%s' % "failed")

                    valueTrSummary << td('%s' % "GOLDEN", bgcolor="grey", align="center")

                    for key in cash.attribute_key:
                        valueTrSummary << td("%s" % standard_cash.getCashAttribute(key), bgcolor="grey", align="center")
                    for key in cash.not_run_attribute_key:
                        valueTrSummary << td("%s" % standard_cash.getCashAttribute(key), bgcolor="grey", align="center")
                    valueTrSummary = tableSummary << tr()
                    valueTrSummary << td('%s' % "RUN", align="center")
                    for key in cash.attribute_key:
                        valueTrSummary << td("%s" % result_cash.getCashAttribute(key), align="center")
                    for key in cash.not_run_attribute_key:
                        tmp = result_cash.getCashAttribute(key)
                        valueTrSummary << td("%s" % tmp, align="center")

                    valueTrSummary = tableSummary << tr()
        span_div = div(style="border:1px ;height:20px")
        page << span_div

        # Display detail information of each bundle/cash
        page << a(name='h_Detail')
        page << div(b('Detail'), id='myCSSid1')

        # bundle detail information
        for bundle_index in self.result_bundle_list:

            if bundle_pass_status[bundle_index]:
                head_color = table_head_color_green
                # titleDiv = div(b('Bundle %d  Passed'%(bundle_index)), id='myCSSid1', style="color:%s"%head_color)
            else:
                head_color = table_head_color_red
                # titleDiv = div(b('Bundle %d Failed'%(bundle_index)), id='myCSSid1', style="color:%s"%head_color)
            # page << titleDiv

            setup_list = self.standard_bundle_list[bundle_index][case.setup_str]
            tearoff_list = self.standard_bundle_list[bundle_index][case.tearoff_str]

            page << a(name='h_bundle%s' % (bundle_index))
            tableBundleDetail = page << table()
            self.tablecss(tableBundleDetail)
            bundleTrDetail = tableBundleDetail << tr()
            bundleTrDetail << td(colspan="2", bgcolor=head_color, align="center") << a("bundle %s" % bundle_index)
            bundleTrDetail << tr()
            bundleTrDetail << td('item', bgcolor=head_color, align="center")
            bundleTrDetail << td('content', bgcolor=head_color, align="center")
            bundleTrDetail << tr()
            bundleTrDetail << td(align="center") << a("cash number")
            bundleTrDetail << td(align="center") << a("%d" % bundle_cash_num[bundle_index])
            bundleTrDetail << tr()
            bundleTrDetail << td(align="center") << a("pass number")
            bundleTrDetail << td(align="center") << a("%d" % bundle_pass_num[bundle_index])
            bundleTrDetail << tr()
            bundleTrDetail << td(align="center") << a("fail number")
            bundleTrDetail << td(align="center") << a(
                "%d" % (bundle_cash_num[bundle_index] - bundle_pass_num[bundle_index]))
            bundleTrDetail << tr()
            bundleTrDetail << td(rowspan="%d" % len(setup_list), align="center") << a("setup commands")
            # bundleTrDetail << td(rowspan="2", align="center") << a("setup commands")
            for cmd in setup_list:
                if self.result_bundle_list[bundle_index][self.setup_str][cmd] == True:
                    bundleTrDetail << td(align="center") << a("%s" % cmd)
                else:
                    bundleTrDetail << td(align="center", bgcolor=table_head_color_red) << a("%s" % cmd)
                bundleTrDetail = tableBundleDetail << tr()
                # bundleTrDetail << tr()
            bundleTrDetail << td(rowspan="%d" % len(tearoff_list), align="center") << a("tearoff commands")
            for cmd in tearoff_list:
                bundleTrDetail << td(align="center") << a("%s" % cmd)
                bundleTrDetail = tableBundleDetail << tr()
                # bundleTrDetail << tr()

            span_div = div(style="border:1px ;height:20px")
            page << span_div
            page << tr()

            titleTrDetail = tableBundleDetail << tr()

            # cash detail information
            for cash_index in self.result_bundle_list[bundle_index]:
                if cash_index == self.setup_str or cash_index == self.tearoff_str:
                    continue
                assert isinstance(cash_index, int)
                assert cash_index > 0
                page << a(name='h_bundle%s_case%d' % (bundle_index, cash_index))
                if self.result_bundle_list[bundle_index][cash_index]:
                    head_color = table_head_color_green
                    titleDiv = div(b('Bundle %s Case %d Passed' % (bundle_index, cash_index)), id='myCSSid1',
                                   style="color:%s" % head_color)
                else:
                    head_color = table_head_color_red
                    titleDiv = div(b('Bundle %s Case %d Failed' % (bundle_index, cash_index)), id='myCSSid1',
                                   style="color:%s" % head_color)
                page << titleDiv

                standard_cash = self.standard_bundle_list[bundle_index][cash_index]
                run_cash = self.run_bundle_list[bundle_index][cash_index]

                tableDetail = page << table()
                self.tablecss(tableDetail)
                titleTrDetail = tableDetail << tr()
                titleTrDetail << td('item', bgcolor=head_color, align="center")
                titleTrDetail << td('GOLDEN', bgcolor=head_color, align="center")
                titleTrDetail << td('RUN', bgcolor=head_color, align="center")
                valueTrDetail = tableDetail << tr()
                for key in cash.attribute_key:
                    valueTrDetail << td("%s" % key, align="center")
                    valueTrDetail << td("%s" % standard_cash.getCashAttribute(key), align="center")
                    valueTrDetail << td("%s" % run_cash.getCashAttribute(key), align="center")
                    valueTrDetail = tableDetail << tr()
                for key in cash.file_path_key:
                    valueTrDetail << td("%s" % key, align="center")
                    valueTrDetail << td(colspan="2", align="center") << a("%s" % standard_cash.geFileAttribute(key))
                    valueTrDetail = tableDetail << tr()
                page << a('Return to Summary', href="#h_summary")
                span_div = div(style="border:1px ;height:50px")
                page << span_div
                page << tr()

        case_logger.info("saving %s" % fileName)
        try:
            page.printOut(fileName)
            if not os.path.exists(fileName):
                raise IOError
        except Exception as e:
            str = "save %s failed!(%s)" % (fileName, e)
            case_logger.error(str)
            raise IOError(str)

        return (all_num, pass_num, fail_num)

    def listenStdout(self, hFun):
        while True:
            sys.stdout.flush()
            lineStr = hFun.stdout.readline().decode()
            self.cmdOutQueue.put(lineStr)

            if "exit" in lineStr or "bye" in lineStr:
                print("退出监听线程")
                break

    def clearStdout(self, times=100):
        # time.sleep(0.01*100)
        time.sleep(0.01)
        str = ""
        while not self.cmdOutQueue.empty():
            str = str + self.cmdOutQueue.get()
        if not str == "":
            command_logger.debug("recv <=" + str)

    def checkCommand(self, times=100):
        n = 0
        while self.cmdOutQueue.empty():
            time.sleep(0.01)
            n = n + 1
            if n > times:
                break
        str = ""
        while not self.cmdOutQueue.empty():
            str = str + self.cmdOutQueue.get()
        command_logger.debug("recv <=" + str)
        if "OK" in str:
            return True
        else:
            # command_logger.error("recv <="+str)
            command_logger.error("command process failed!")
            return False

    def checkRunCommand(self, bundle_index, cash_index):
        # time.sleep(0.5)
        times = 100
        n = 0
        while self.cmdOutQueue.empty():
            time.sleep(0.01)
            n = n + 1
            if n > times:
                break
        str = ""
        str = str + self.cmdOutQueue.get()
        # while not cmdOutQueue.empty():
        # str = str + cmdOutQueue.get()
        command_logger.debug("recv <=" + str)
        if "OK" not in str:
            command_logger.error("recv <=" + str)
            command_logger.error("run command process failed!")
            return False

        str = str.lstrip().rstrip()
        index = str.find("command:")
        if index < 0:
            command_logger.error("recv <=" + str)
            command_logger.error("command process failed! can NOT find \'command\' in return string")
            return False
        str = str[index + 8:]
        retList = str.split()
        retDict = {}
        for element in retList:
            if ":" in element:
                temp = element.split(":")
                # # 1.15暂时这么做
                # if temp[-2] == self.version_str and temp[-1] == "5":
                #     temp[-1] = "05"
                retDict[temp[-2]] = temp[-1]

        for key in retDict:
            if key in cash.attribute_key:
                self.run_bundle_list[bundle_index][cash_index].setCashAttribute(key, retDict[key])

        return True

    # wwm 1.14 边查边写入  根据数目创建x的standrad变量
    def load_yaml_smallcasepath(self, file_yaml):
        y = yaml.YAML()
        y.allow_duplicate_keys = False
        try:
            with open(file_yaml, 'r') as infile:
                try:
                    yaml_dict = y.load(infile)
                    self.case_file = file_yaml
                except Exception as e:
                    error_str = "%s format error!(%s)" % (file_yaml, e)
                    case_logger.error(error_str)
                    raise YamlFormatError(error_str)
        except IOError as e:
            error_str = "open file %s failed! (%s)\n" % (file_yaml, e)
            case_logger.error(error_str)
            raise e
        except Exception as e:
            error_str = "Error in case.loadFromYaml(%s)" % e
            case_logger.error(error_str)
            raise Exception(error_str)

        try:
            yaml_description_dict = yaml_dict[self.description_str]
            yaml_information_dict = yaml_dict[self.information_str]
            yaml_bundle_dict = yaml_dict[self.bundle_str]

            for key in self.description_key:
                try:
                    self.description[key] = yaml_description_dict[key]
                except Exception as e:
                    self.description[key] = ''

            for key in self.information_key:
                self.information[key] = yaml_information_dict[key]

            # for bundle_key in yaml_dict[self.bundle_str]:
            #     if operator.eq("bundle", bundle_key[0:5]):
            #         raise YamlFormatError("Expect token \"bundle\", but \"%s\" found." % (bundle_key[0:5]))
            #     try:
            #         bundle_index = int(bundle_key[6:])
            #     except Exception as e:
            #         raise YamlFormatError("Expect token \"bundle+integer\", but \"%s\" found." % (bundle_key))
            #     bundle = self.newBundle(bundle_index)
            #     self.standard_bundle_list[bundle_index][self.setup_str] = yaml_bundle_dict[bundle_key][self.setup_str]
            #     self.standard_bundle_list[bundle_index][self.tearoff_str] = yaml_bundle_dict[bundle_key][
            #         self.tearoff_str]
            setup_command=[]
            tearoff_command=[]
            for bundle_key in yaml_dict[self.bundle_str]:
                setup_command = yaml_bundle_dict[bundle_key][self.setup_str]
                tearoff_command = yaml_bundle_dict[bundle_key][
                        self.tearoff_str]
            # 将bundle创建多个（为路径）
            self.get_self_bundle_list(setup_command,tearoff_command)

            #11.18 wwm


        except Exception as e:
            error_str = "Error in case.loadFromYaml(%s)" % e
            case_logger.error(error_str)
            raise Exception(error_str)
            # return False

        return True

    def caculate_total_num(self, file_yaml):
        """
        总方法：计算总数
        :param file_yaml:
        :return:num
        """
        y = yaml.YAML()
        y.allow_duplicate_keys = False
        try:
            with open(file_yaml, 'r') as infile:
                try:
                    yaml_dict = y.load(infile)
                    self.case_file = file_yaml
                except Exception as e:
                    error_str = "%s format error!(%s)" % (file_yaml, e)
                    case_logger.error(error_str)
                    raise YamlFormatError(error_str)
        except IOError as e:
            error_str = "open file %s failed! (%s)\n" % (file_yaml, e)
            case_logger.error(error_str)
            raise e
        except Exception as e:
            error_str = "Error in case.loadFromYaml(%s)" % e
            case_logger.error(error_str)
            raise Exception(error_str)
        try:
            yaml_description_dict = yaml_dict[self.description_str]
            yaml_information_dict = yaml_dict[self.information_str]
            yaml_bundle_dict = yaml_dict[self.bundle_str]


        except Exception as e:
            error_str = "Error in case.loadFromYaml(%s)" % e
            case_logger.error(error_str)
            raise Exception(error_str)
            # return False

        return self.caculate_total(yaml_description_dict[self.search_path_str])

    def caculate_total(self, path):
        """
        计算path下样本总数
        :param fileName:
        :param path:
        :return:
        """
        # 获取信息模式  0 文件夹匹配 1 文件匹配
        assert os.path.exists(path)
        index = 0
        count_total = 0
        for parent, dirnames, filenames in os.walk(path):
            #  wwm 10.24 读取文件夹信息
            if not filenames:
                continue
            for filename in filenames:
                name, ext = os.path.splitext(filename)
                if ".raw" == ext and "adc0" in name:
                    index = index + 1
                    count_total += 1

        return count_total
